# _*_ coding: utf-8 _*_
"""
@ 时间    ：2024/10/26 10:44
@ 作者    ：旺财
@ 文件    ：03 DBSCAN算法.py
@ 说明    ：算法原理：以密度为基础的空间聚类算法，将具有足够密度大区域划分为簇，且将不属于任何一簇的数据(噪声点)剔除
"""
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans, DBSCAN

# 1. 读取数据
df = pd.read_excel('演示数据.xlsx')
print(df.head())

# 2. 定义画布,绘制原始图
plt.rcParams['font.sans-serif'] = ['SimHei']
_, axs = plt.subplots(1, 3, figsize=(15, 5))

axs[0].scatter(df.iloc[:, 0], df.iloc[:, 1], c='green', marker='*')
axs[0].set_title('原图')
axs[0].set_xlabel('x')
axs[0].set_ylabel('y')
axs[0].legend(['样本'], loc=2)

# 3. KMeans聚类
kms = KMeans(n_clusters=2, random_state=123)
kms.fit(df)
label = kms.labels_
print(label)

# 4.绘制KMeans分类图
axs[1].scatter(df[label == 0].iloc[:, 0], df[label == 0].iloc[:, 1], c='green', marker='*')
axs[1].scatter(df[label == 1].iloc[:, 0], df[label == 1].iloc[:, 1], c='red', marker='o')
axs[1].set_title('KMeans聚类')
axs[1].set_xlabel('x')
axs[1].set_ylabel('y')
axs[1].legend(['类别1', '类别2'], loc=2)

# 5. DBSCAN聚类
dbs = DBSCAN()
dbs.fit(df)
label = dbs.labels_
print(label)

# 6. 绘制DBSCAN分类图
axs[2].scatter(df[label == 1].iloc[:, 0], df[label == 1].iloc[:, 1], c='green', marker='*')
axs[2].scatter(df[label == 0].iloc[:, 0], df[label == 0].iloc[:, 1], c='red', marker='o')
axs[2].set_title('DBSCAN聚类')
axs[2].set_xlabel('x')
axs[2].set_ylabel('y')
axs[2].legend(['类别1', '类别2'], loc=2)

plt.show()

